package com.jws.jawestshow;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Display;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.widget.Button;
import android.text.TextUtils;
import java.util.List;
import android.view.WindowManager;
import android.os.Environment;

import com.jws.jawestshow.R;

public class CameraActivity extends Activity {
	private Camera mCamera;
	private Camera.Parameters mCameraParam;
	private SurfaceHolder.Callback surfaceCallback;
	private SurfaceHolder surfaceHolder;
	private SurfaceView surfaceView;
	private String mISO = "AUTO";
	private Button mButtonOpen;
	private Button mButtonClose;
	private static final int DISPLAY_ORIENTATION = 90;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera);
		initCameraViews();
		initButton();
	}
	private void initButton()
	{
		mButtonOpen = (Button) findViewById(R.id.open);
		mButtonClose = (Button) findViewById(R.id.close);
		mButtonOpen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCamera.stopPreview();
				mCamera.startPreview();
			}
		});

		mButtonClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCamera.stopPreview();
			}
		});
		
	}
	
	class SurfaceCallback implements SurfaceHolder.Callback
	{
		public void surfaceChanged(SurfaceHolder paramSurfaceHolder, int paramInt1, int paramInt2, int paramInt3)
		{
			startPreview();
		}

		public void surfaceCreated(SurfaceHolder paramSurfaceHolder)
		{
				openCamera();
			try {
				mCamera.setPreviewDisplay(paramSurfaceHolder);
			} catch (IOException exception) {
				closeCamera();
			}
		}

		public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder)
		{
			if (mCamera == null)
			return;
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
			surfaceHolder =null;
		}
	}
	  
  private void initCameraViews()
  {
    surfaceCallback = new SurfaceCallback();
    surfaceView = (SurfaceView)findViewById(R.id.camera_preview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(surfaceCallback);
    surfaceHolder.setType(3);
  }
  
  private void openCamera() 
  {
      if (mCamera == null) 
	  {
          mCamera = Camera.open();
          mCameraParam = mCamera.getParameters();
        //  mCameraParam.setFlashMode(Parameters.FLASH_MODE_ON);
          Intent intent = getIntent();
          try {
              mISO = intent.getStringExtra("ISO");
              if (TextUtils.isEmpty(mISO)) {
                  mISO = "AUTO";
              }

          } catch (Exception e) {
              mISO = "AUTO";

          }
          if (null != mCameraParam && null != mCamera)
          {
              mCamera.setParameters(mCameraParam);
          }
      }

  }

  private void closeCamera() {
      if (null != mCamera) {
          mCamera.release();
          mCamera = null;
      }
  }
	
  private void startPreview() 
  {
      if (null != mCamera) 
	  {
          mCameraParam = mCamera.getParameters();
          Size size = mCameraParam.getPictureSize();
          List<Size> sizes = mCameraParam.getSupportedPreviewSizes();
          Size optimalSize = null;
          if (size != null && size.height != 0)
              optimalSize = getOptimalPreviewSize(sizes, (double) size.width / size.height);
          if (optimalSize != null) {
              mCameraParam.setPreviewSize(optimalSize.width, optimalSize.height);
          }
          mCameraParam.set("fps-mode", 0); 
          mCameraParam.set("cam-mode", 0);
          mCamera.setParameters(mCameraParam);
		  mCamera.setDisplayOrientation(DISPLAY_ORIENTATION);
       }
  } 

  private Camera.Size getOptimalPreviewSize(List<Size> sizes, double targetRatio)
  {
      final double ASPECT_TOLERANCE = 0.05;
      if (sizes == null) return null;
      Size optimalSize = null;
      double minDiff = Double.MAX_VALUE;
      Display display = getWindowManager().getDefaultDisplay();
      int targetHeight = Math.min(display.getHeight(), display.getWidth());
      if (targetHeight <= 0) {
          WindowManager windowManager = (WindowManager)
                  getSystemService(Context.WINDOW_SERVICE);
          targetHeight = windowManager.getDefaultDisplay().getHeight();
      }
      for (Size size : sizes) {
          if (targetHeight > size.height) continue;
          
          double ratio = (double) size.width / size.height;
          if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
          if (Math.abs(size.height - targetHeight) < minDiff) {
              optimalSize = size;
              minDiff = Math.abs(size.height - targetHeight);
          }
      }

      if (optimalSize == null) {
          for (Size size : sizes) {
              double ratio = (double) size.width / size.height;
              if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
              if (Math.abs(size.height - targetHeight) < minDiff) {
                  optimalSize = size;
                  minDiff = Math.abs(size.height - targetHeight);
              }
          }
      }

      if (optimalSize == null) {
          minDiff = Double.MAX_VALUE;
          for (Size size : sizes) {
              if (Math.abs(size.height - targetHeight) < minDiff) {
                  optimalSize = size;
                  minDiff = Math.abs(size.height - targetHeight);
              }
          }
      }
      return optimalSize;
  }
}
